package org.misty.spring.redis.config;

import org.misty.bloomfilter.BloomFilter;
import org.misty.bloomfilter.JedisAdapter;
import org.misty.bloomfilter.JedisPoolAdapter;
import org.misty.bloomfilter.RedisTemplateAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPool;

@Configuration
public class BloomFilterConfigurer {
    @Bean
    public BloomFilter jedis(JedisConnectionFactory factory) {
        var conn = (JedisConnection) factory.getConnection();
        var jedis = conn.getJedis();
        var client = new JedisAdapter(jedis);
        var config = new BloomConfig();
        return new BloomFilter(client, config);
    }

    @Bean
    public BloomFilter jedisPool(JedisConnectionFactory factory) throws Exception {
        var f = JedisConnectionFactory.class.getDeclaredField("pool");
        f.setAccessible(true);
        var pool = f.get(factory);
        if (pool == null) {
            pool = new JedisPool("192.168.0.106", 6379);
        }
        var client = new JedisPoolAdapter((JedisPool) pool);
        var config = new BloomConfig();
        return new BloomFilter(client, config);
    }

    @Bean
    public BloomFilter template(StringRedisTemplate redisTemplate) {
        var client = new RedisTemplateAdapter(redisTemplate);
        return new BloomFilter(client, new BloomConfig());
    }

    static class BloomConfig implements BloomFilter.IConfig {
        @Override
        public long getExpectedInsertions() {
            return 1000;
        }

        @Override
        public double getFpp() {
            return 0.01;
        }

        @Override
        public String getRedisKey() {
            return "testBloomFilter";
        }
    }
}
